<?php

namespace app\api\model;

use app\common\enums\StatusEnum;
use app\common\controller\Send;
use app\api\service\Token;
use think\Db;

class Userinfo extends \app\common\model\Userinfo
{
    
    use send;
    const CODE_PHONE_BIND = 3; //手机绑定
    /**
     * 用户登录授权
     * @param $phone
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function updateUserInfo($data)
    {
        
        $user = self::getByUid($data['uid']);
        if (empty($user)) {
            return self::sendResult(141,[],'用户不存在');
        }
        $user->uid = $data['uid'];
        $user->head_img = isset($data['head_img']) ? $data['head_img'] : '';
        $user->nickname = isset($data['nickname']) ? $data['nickname'] : '';
        $user->sex = isset($data['sex']) ? $data['sex'] : '';
        $user->address = isset($data['address']) ? $data['address'] : '';
        $user->signature = isset($data['signature']) ? $data['signature'] : '';
        $retData = $user->save();
        if($retData>0){
            return self::sendResult(self::$okCode, [],'更新成功');
        }else{
            return self::sendResult(141, [],'更新失败');
        }
        
        
    }
    
    /**
     * 用户修改密码
     * @param $phone
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function updateUserPwd($data)
    {
    
        $user = self::getByUid($data['uid']);
        if (empty($user)) {
            return self::sendResult(141,[],'用户不存在');
        }
        $pwd = $user['password'];
        if($pwd != MD5($data['password'])){
            return self::sendResult(141,[],'旧密码不正确');
        }
        if($data['new_password'] != $data['repassword']){
            return self::sendResult(141,[],'新密码两次输入不一致');
        }
        $user->id = $data['uid'];
        $user->password = MD5($data['new_password']);
        $retData = $user->save();
        if($retData>0){
            return self::sendResult(self::$okCode, [],'更新成功');
        }else{
            return self::sendResult(141, [],'更新失败');
        }
    
    
    }
    /**
     * 用户添加密码
     * @param $phone
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function addUserPwd($user,$data)
    {

        $user = self::getByUid($user['id']);
        if (empty($user)) {
            return self::sendResult(141,[],'用户不存在');
        }

        $pwd = $user['password'];
        $user->id = $user['id'];
        $user->password = MD5($data['password']);
        $retData = $user->save();
        if($retData>0){
            return self::sendResult(self::$okCode, [],'添加成功');
        }else{
            return self::sendResult(202, [],'添加失败');
        }
    }
    
    /**
     * 绑定微信
     * @param $phone
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function bindWechat($data)
    {
    
        $user = self::getByUid($data['uid']);
        if (empty($user)) {
            return self::sendResult(141,[],'用户不存在');
        }
        $unionInfo = self::getByUnionid($data['unionid']);
        if($unionInfo && ($unionInfo['id']!=$data['uid'])){
            $fphone = substr($user['phone'], 0,3).'****'.substr($user['phone'], 7,4);
            $sphone = substr($unionInfo['phone'], 0,3).'****'.substr($unionInfo['phone'], 7,4);
            $msg = "此微信号已绑定".$fphone."手机账号,是否放弃原账号?放弃后数据将同步到".$sphone."当前账号下";
            $reData['old_uid'] = $unionInfo['id'];
            $reData['new_uid'] = $user['id'];
            return self::sendResult(141,$reData,$msg);
        }
        
        if($user['unionid']){
            $userinfo['nickname'] = $user['nickname'];
            return self::sendResult(self::$okCode,$userinfo,'用户已绑定微信');
        }else{
            $user->uid = $data['uid'];
            $user->unionid = $data['unionid'];
            $user->head_img = isset($data['head_img']) ? $data['head_img'] : '';
            $user->nickname = isset($data['nickname']) ? $data['nickname'] : '';
            $retData = $user->save();
            if($retData>0){
                return self::sendResult(self::$okCode, [],'绑定成功');
            }else{
                return self::sendResult(141, [],'绑定失败');
            }
        }
    
    }
    
    
    /**
     * 是否绑定微信
     * @param $phone
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function isBindWechat($data)
    {
    
        $user = self::getByUid($data['uid']);
        if (empty($user)) {
            return self::sendResult(141,[],'用户不存在');
        }
        if($user['unionid']){
            $userinfo['nickname'] = $user['nickname'];
            return self::sendResult(self::$okCode,$userinfo,'用户已绑定微信');
        }else{
            return self::sendResult(141, [],'未绑定');
        
        }
    
    }
    
    
    /**
     * 绑定设备
     * @param $phone
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function bindDevice($data)
    {
    
        $user = self::getByUid($data['uid']);
        if (empty($user)) {
            return self::sendResult(141,[],'用户不存在');
        }
        $user->id= $data['uid'];
        $user->device_info= $data['device_info'];
        $user->is_bind_device= 1;
        $user->update_time= time();
        $retData = $user->save();
        if($retData>0){
            $where['device_info'] = $data['device_info'];
            $where['is_bind_device'] = 0;
            $orderInfo = DB::table('oauth')->field('id')->where($where)->find();
            $order_where['oauth_id'] = $orderInfo['id'];
            $save_data['oauth_id'] = $data['uid'];
            DB::table('oauth_order')->where($order_where)->update($save_data);
            DB::table('oauth_order_class')->where($order_where)->update($save_data);
            return self::sendResult(self::$okCode, [],'绑定成功');
        }else{
            return self::sendResult(141, [],'绑定失败');
        }
    
    
    }
    
    
    /**
     * 是否绑定设备
     * @param $phone
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function isBindDevice($data)
    {
    
        $user = self::getByUid($data['uid']);
        if (empty($user)) {
            return self::sendResult(141,[],'用户不存在');
        }
        if($user['device_info']){
            $userinfo['device_info'] = $user['device_info'];
            return self::sendResult(self::$okCode,$userinfo,'用户已绑定设备');
        }else{
            return self::sendResult(141, [],'未绑定');
    
        }
    
    }
    
    
    
    /**
     * 绑定设备
     * @param $phone
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function untieWechat($data)
    {
    
        $user = self::getByUid($data['uid']);
        if (empty($user)) {
            return self::sendResult(141,[],'用户不存在');
        }
        $user->id= $data['uid'];
        $user->unionid= '';
        $user->nickname= '';
        $user->head_img= '';
        $retData = $user->save();
        if($retData>0){
            return self::sendResult(self::$okCode, [],'解绑成功');
        }else{
            return self::sendResult(141, [],'绑定失败');
        }
    
    
    }
    
    
    /**
     * 绑定电话
     * @param $phone
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function bindPhone($data)
    {
        
        $code = $data['code'];
        $sess_code= json_decode(cache(self::CODE_PHONE_BIND.$data['phone']), true);
        //print_r($code);exit();
        if($code != $sess_code){
            return self::sendResult(-2, [], '验证码不正确');
        }
        if($data['password'] != $data['repassword']){
            return self::sendResult(141, [],'两次输入密码不一致');
        }
        
        $uidInfo = self::getByUid($data['uid']);
        $user = self::getByPhone($data['phone']);//手机是否绑定
        $token = Token::generateToken();
        if ($user) {
            //旧用户绑定微信号
            $uid  = $user['id'];
            $saveData['unionid']= $uidInfo['unionid'];
            $saveData['nickname']= $uidInfo['nickname'];
            $saveData['head_img']= $uidInfo['head_img'];
            $saveData['password']= MD5($data['password']);
            $saveData['apple_user_id'] = $uidInfo['apple_user_id'];
            $saveData['email'] = $uidInfo['email'];
            $where['id'] =  $uid;
            $retData = static::where($where)->update($saveData);
            cache($token, $uid, 86400);
            self::deleteOne($uidInfo['id']);
            $returnData = [
                'uid' => $uid,
                'nickname' => $uidInfo['nickname'],
                'sex' => $user['sex'],
                'province' => $user['province'],
                'city' => $user['city'],
                'country' => $user['country'],
                'headImg' => $uidInfo['head_img'],
                'phone' => $data['phone'],
                'shareKey' => self::shareKey(),
                'autoplay' => $user['autoplay']?1:0,
                'hasMobile' => 1,
                'token' => $token,
            ];
            return self::sendResult(self::$okCode,$returnData,'成功');
        }else{
            $uid  = $uidInfo['id'];
            $where['id'] =  $uid;
            $saveData['phone']=$data['phone'];
            $saveData['password']=MD5($data['password']);
            $retData = static::where($where)->update($saveData);
            cache($token, $uid, 86400);
            $returnData = [
            'uid' => $uid,
            'nickname' => $uidInfo['nickname'],
            'sex' => $uidInfo['sex'],
            'province' => $uidInfo['province'],
            'city' => $uidInfo['city'],
            'country' => $uidInfo['country'],
            'headImg' => $uidInfo['head_img'],
            'shareKey' => self::shareKey(),
            'phone' => $data['phone'],
            'autoplay' => $uidInfo['autoplay']?1:0,
            'hasMobile' => 1,
            'token' => $token,
            ];
            if($retData>0){
                return self::sendResult(self::$okCode, $returnData,'成功');
            }else{
                return self::sendResult(141, [],'绑定失败');
            }
        }
    }
    
    
    
    /**
     * 放弃原来的账号绑定新账号
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function repeatNewAccount($data)
    {
    
        $old_user = self::getByUid($data['old_uid']);
        $new_user = self::getByUid($data['new_uid']);
        if (empty($old_user) || empty($new_user)) {
            return self::sendResult(141,[],'新用户或者旧用户不存在');
        }
        if(empty($old_user['unionid'])) return self::sendResult(141,[],'旧用户没有绑定微信号');
        $token = Token::generateToken();
        $new_user->id= $new_user['id'];
        $new_user->unionid= $new_user['unionid'];
        $new_user->nickname= $old_user['nickname'];
        $new_user->head_img= $old_user['head_img'];
        $new_user->save();
        $old_user->id= $old_user['id'];
        $old_user->unionid= '';
        $old_user->nickname= '';
        $old_user->head_img= '';
        $old_user->save();
        cache($token, $new_user['id'], 86400);
        $returnData = [
            'uid' => $new_user['id'],
            'nickname' => $old_user['nickname'],
            'sex' => $new_user['sex'],
            'province' => $new_user['province'],
            'city' => $new_user['city'],
            'country' => $new_user['country'],
            'headImg' => $old_user['head_img'],
            'shareKey' => self::shareKey(),
            'autoplay' => $new_user['autoplay']?1:0,
            'hasMobile' => 1,
            'token' => $token,
        ];
        return self::sendResult(self::$okCode, $returnData,'成功');
    
    }
    
    
    /**
     * 游客是否购买课程
     * @param $phone
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function isBuyClass($data)
    {
    
        $user = self::getByUid($data['uid']);
        if (empty($user)) {
            return self::sendResult(141,[],'用户不存在');
        }
        if(empty($user['device_info'])){
            return self::sendResult(141, [],'未找到该设备');
        }
        $where['oauth_id'] = $data['uid'];
        $orderInfo = DB::table('oauth_order')->field('order_sn,oauth_id AS uid,money')->where($where)->select();
        if($orderInfo){
            return self::sendResult(self::$okCode, $orderInfo,'成功');
        }else{
            return self::sendResult(141, '','未有购买课程信息');
        }
    }
    
    /**
     * 设备是否绑定账号
     * @param $phone
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function isBindDeviceInfo($data)
    {
    
        
        $device_info = self::getByDevice($data['device_info']);
        if ($device_info>1) {
            return self::sendResult(141,[],'已经绑定过');
        }else{
            return self::sendResult(self::$okCode,'','未绑定');
        }    
    }
    
    /**
     * id随机key
     * @param int $length 长度
     * @return string
     * @throws \think\Exception\DbException
     */
    private static function shareKey($length = 10)
    {
        $key = rand_char($length);
        $next = true;
        while ($next) {
            $model = Oauth::where(['share_key' => $key])->find();
            if (empty($model)) {
                $next = false;
            } else {
                $key = rand_char($length);
            }
        }
        return $key;
    }
    
    
    
    
    
  
 
}